import logging

from celery._state import get_current_task


class CeleryFormatter(logging.Formatter):

    def format(self, record):
        task = get_current_task()
        if task and task.request and task.request.id:
            record.__dict__.update(
                task_id='%s' % task.request.id,
                task_name='%s' % task.name,
                # params='%s' % f'{task.request.args}|{task.request.kwargsrepr}',
                # params='%s' % f'{repr(task.request.argsrepr)}|{repr(task.request.kwargs)}',
            )
        else:
            record.__dict__.setdefault('task_name', '')
            record.__dict__.setdefault('task_id', '')
            # record.__dict__.setdefault('params', '')
        return super().format(record)

    pass


DICT_CONFIG = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'default': {
            'class': 'project.logger.CeleryFormatter',
            'format': '%(asctime)s %(levelname)8s %(filename)16s:%(lineno)3d [%(task_id)s|%(task_name)s] - %(message)s',
            'style': '%',
        },
    },

    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'default',
        },

    },
    'loggers': {
        'console': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
    },
    'root': {
        'handlers': ['console', ],
        'level': 'INFO',
    },
}
